package com.example.albumhotpro;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity {
	private ProgressDialog pDialog;
	ArrayList<Album> listAlbum;
	JSONObject jsonobject;
	JSONArray jsonarray;
	ListView lv;
	ProgressDialog mProgressDialog;
	AlbumAdapter adapter;
	// ListViewAdapter adapter;
	private Context mCon;
	private static String url = "http://service2.topprinter.org/album-rest";
	final int CONTEXT_MENU_DELETE = 1;
	final int CONTEXT_MENU_RENAME = 2;
	final int CONTEXT_MENU_ADD = 3;
	Menu mymenu;
	private MenuItem refreshMenuItem;
	private ActionBar actionBar;
	final AsyncHttpClient client = new AsyncHttpClient();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listAlbum = new ArrayList<Album>();
		final Album viewAl = new Album();
		lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String id1 = ((TextView) view.findViewById(R.id.id)).getText()
						.toString();
				String artist = ((TextView) view.findViewById(R.id.artist))
						.getText().toString();
				String title = ((TextView) view.findViewById(R.id.title))
						.getText().toString();
				Intent in = new Intent(getApplicationContext(),
						ItemChildsAlbum.class);
				in.putExtra(viewAl.getId(), id1);
				in.putExtra(viewAl.getArtist(), artist);
				in.putExtra(viewAl.getTitle(), title);
				startActivity(in);
			}
		});
		actionBar = getActionBar();
		registerForContextMenu(lv);
		client.get(url, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				pDialog = new ProgressDialog(MainActivity.this);
				pDialog.setMessage("Please wait...");
				pDialog.setCancelable(false);
				pDialog.show();
			}

			@Override
			public void onSuccess(String resultMessage) {
				JSONObject jsonObj;
				try {
					jsonObj = new JSONObject(resultMessage);
					jsonarray = jsonObj.getJSONArray("data");
					for (int i = 0; i < jsonarray.length(); i++) {
						Album album = new Album();
						jsonobject = jsonarray.getJSONObject(i);
						album.setId(jsonobject.getString("id"));
						album.setArtist(jsonobject.getString("artist"));
						album.setTitle(jsonobject.getString("title"));
						listAlbum.add(album);
					}
				} catch (JSONException e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
				if (pDialog.isShowing())
					pDialog.dismiss();
				adapter = new AlbumAdapter(MainActivity.this,
						R.layout.list_item, listAlbum);
				lv.setAdapter(adapter);
			}

			@Override
			public void onFailure(Throwable e, String resultMessage) {
				Log.i("onFailure", resultMessage);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		Album album = new Album();
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		searchView.setIconifiedByDefault(true);

		SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				if (newText != null && newText.toString().length() > 0) {
					ArrayList<Album> arrayTemplist = new ArrayList<Album>();
					String filterString = newText.toString().toLowerCase();
					String filterableString;
					for (int i = 0; i < listAlbum.size(); i++) {
						filterableString = listAlbum.get(i).getTitle();
						if (filterableString.trim().toLowerCase()
								.startsWith(filterString.trim().toLowerCase())) {
							arrayTemplist.add(listAlbum.get(i));
						}
					}
//					adapter = new ListViewAdapter(MainActivity.this,
//							arrayTemplist);
					adapter = new AlbumAdapter(MainActivity.this,
							R.layout.list_item, arrayTemplist);
					lv.setAdapter(adapter);
				} else {
					return false;
				}
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				return true;
			}
		};
		searchView.setOnQueryTextListener(textChangeListener);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			refreshMenuItem = item;
			new Loaddata().execute();
			return true;
		case R.id.action_settings:

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
		menu.add(Menu.NONE, CONTEXT_MENU_RENAME, Menu.NONE, "Rename");
		menu.add(Menu.NONE, CONTEXT_MENU_ADD, Menu.NONE, "Add");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AsyncHttpClient client = new AsyncHttpClient();
		Album album = new Album();
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		Long id = lv.getAdapter().getItemId(info.position);
		album = listAlbum.get(Integer.valueOf(id.intValue()));
		final int number_of_item_in_listview = Integer.valueOf(id.intValue());
		switch (item.getItemId()) {
		case CONTEXT_MENU_DELETE:
			client.delete(
					"http://service2.topprinter.org/album-rest/"
							+ album.getId(), new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(String response) {
							Log.i("thanh cong", response + ":"
									+ number_of_item_in_listview);
						}

						@Override
						public void onFailure(Throwable e, String response) {
							Log.i("onFailure", response);
						}
					});

			listAlbum.remove(number_of_item_in_listview);
			adapter.notifyDataSetChanged();
			return (true);
		case CONTEXT_MENU_RENAME:
			final Album album1 = new Album();
			LayoutInflater layoutInflater = LayoutInflater.from(this);
			View promptView = layoutInflater.inflate(R.layout.alertbox, null);
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Rename Artist Album");
			final EditText editID = (EditText) promptView
					.findViewById(R.id.edtID);
			editID.setText(album.getId());
			editID.setEnabled(false);
			final EditText editARTIST = (EditText) promptView
					.findViewById(R.id.edtARTIST);
			final EditText editTITLE = (EditText) promptView
					.findViewById(R.id.edtTITLE);
			alert.setView(promptView);
			alert.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							album1.setId(editID.getText().toString());
							album1.setArtist(editARTIST.getText().toString());
							album1.setTitle(editTITLE.getText().toString());
							RequestParams params = new RequestParams();
							params.add("id", editID.getText().toString());
							params.add("artist", editARTIST.getText()
									.toString());
							params.add("title", editTITLE.getText().toString());
							// params.put("id", "20");
							// params.put("artist", "bbb");
							// params.put("title", "ccc");
							Log.i("params", "before:" + params);
							client.post(url, params,
									new AsyncHttpResponseHandler() {
										@Override
										public void onSuccess(String response) {
											Log.i("onSuccess", "resultp: "
													+ album1.getId());
											Log.i("onSuccess", "response: "
													+ response);
										}

										@Override
										public void onFailure(Throwable error,
												String content) {
											Log.i("onFailure", content);
										}
									});
							Log.i("params", "after:" + params);
							listAlbum.set(number_of_item_in_listview, album1);
							adapter.notifyDataSetChanged();
						}
					});
			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.cancel();
						}
					});
			alert.show();
			return (true);
		case CONTEXT_MENU_ADD:
			final Album album2 = new Album();
			LayoutInflater layoutInflaterAdd = LayoutInflater.from(this);
			View promptViewAdd = layoutInflaterAdd.inflate(R.layout.addbox,
					null);
			AlertDialog.Builder alertAdd = new AlertDialog.Builder(this);
			final EditText addARTIST = (EditText) promptViewAdd
					.findViewById(R.id.iedtartist);
			final EditText addTITLE = (EditText) promptViewAdd
					.findViewById(R.id.iedttitle);
			alertAdd.setView(promptViewAdd);
			alertAdd.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							album2.setId("0");
							album2.setArtist(addARTIST.getText().toString());
							album2.setTitle(addTITLE.getText().toString());
							RequestParams params = new RequestParams();
							params.add("id", "0");
							params.add("artist", addARTIST.getText().toString());
							params.add("title", addTITLE.getText().toString());
							Log.i("params", "before:" + params);
							client.post(url, params,
									new AsyncHttpResponseHandler() {
										@Override
										public void onSuccess(String response) {
											Log.i("onSuccess", "response: "
													+ response);
										}

										@Override
										public void onFailure(Throwable error,
												String content) {
											Log.i("onFailure", content);
										}
									});
							Log.i("params", "after:" + params);
							listAlbum.set(number_of_item_in_listview, album2);
							adapter.notifyDataSetChanged();
						}
					});
			alertAdd.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.cancel();
						}
					});

			alertAdd.show();
			return (true);
		}	
		return (super.onOptionsItemSelected(item));
	}

	private class Loaddata extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			refreshMenuItem.setActionView(R.layout.progressbar);
			refreshMenuItem.expandActionView();
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			refreshMenuItem.collapseActionView();
			refreshMenuItem.setActionView(null);
		}
	};
}
